package org.road0329.dlt698.sessionlayer.hdlc;

import org.road0329.dlt698.DataUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.ByteBuffer;
import java.util.Locale;

public class HdlcAddress {
    private static Logger logger = LoggerFactory.getLogger(HdlcAddress.class);
    private int byteLength = 0;
    private int logicalDeviceAddress = 0;
    private String physicalDeviceAddress = "";

    public HdlcAddress(int logicalDeviceAddress, String physicalDeviceAddress) {
        this.byteLength = physicalDeviceAddress.length() % 2 == 0 ? physicalDeviceAddress.length() / 2 : (physicalDeviceAddress.length() + 1) / 2;
        ++ this.byteLength;
        this.logicalDeviceAddress = logicalDeviceAddress;
        this.physicalDeviceAddress = physicalDeviceAddress;
    }

    public int getLogicalDeviceAddress() {
        return this.logicalDeviceAddress >> 4 & 0x30;
    }

    public int getAddressType() {
        return this.logicalDeviceAddress >> 6 & 0x3;
    }

    public void setAddressType(int addressType) {
        this.logicalDeviceAddress = (this.logicalDeviceAddress & 0x3F | (addressType & 0x3) << 6);
    }

    public String getPhysicalDeviceAddress() {
        return this.physicalDeviceAddress;
    }

    public int getByteLength() {
        return this.byteLength;
    }

    public static HdlcAddress decode(ByteBuffer data) {
        int logicalDeviceAddr;
        String physicalDevAddr;
        logicalDeviceAddr = data.get(0) & 0x30;
        int addlen = (data.get(0) & 0xF) + 1;
        physicalDevAddr = DataUtils.toShortHexString(data.array(), 1, addlen, true);
        return new HdlcAddress(logicalDeviceAddr, physicalDevAddr);
    }

    public ByteBuffer encode() throws Exception {
        int firstaddr;
        ByteBuffer result = ByteBuffer.allocate(this.byteLength);
        firstaddr = this.logicalDeviceAddress & 0xF0;
        firstaddr = firstaddr | this.byteLength - 2 & 0xF;
        result.put(0, (byte) firstaddr);
        if (this.physicalDeviceAddress.length() % 2 == 1) {
            this.physicalDeviceAddress += "F";
        }
        System.out.println(this.physicalDeviceAddress);
        byte[] srvaddr = DataUtils.fromShortHexString(this.physicalDeviceAddress, true);
        for (int i = 0; i < srvaddr.length; i++) {
            result.put(i + 1, srvaddr[i]);
        }
        return result;
    }

    @Override
    public String toString() {
        String s = "";
        int phLength = this.byteLength / 2 * 2;
        s += String.format("%02X", this.logicalDeviceAddress);
        if (phLength > 0) {
            s += "-" + this.physicalDeviceAddress;
        }
        return s;
    }
}



